//
//  GRStartView.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/7/26.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRStartView.h"

@interface  GRStartView()
@property(nonatomic,strong)UIImage * starHighLightImage;
@property(nonatomic,strong)UIImage * starGrayImage;
@property(nonatomic,strong)UIImage * starNormalImage;
@property(nonatomic,assign)CGFloat percent;
@property(nonatomic,assign)BOOL isGray;
@end
@implementation GRStartView
-(UIImage *)starGrayImage{
    if (!_starGrayImage) {
        _starGrayImage = [UIImage imageNamed:@"starGray"];
    }
    return _starGrayImage;
}

-(UIImage *)starNormalImage{
    if (!_starNormalImage) {
        _starNormalImage = [UIImage imageNamed:@"starNomal"];
    }
    return _starNormalImage;
}

-(UIImage *)starHighLightImage{
    if (!_starHighLightImage) {
        _starHighLightImage = [UIImage imageNamed:@"starHight"];
    }
    return _starHighLightImage;
}

-(void)setPercent:(CGFloat)percent IsGray:(BOOL)isGray{
    self.isGray = isGray;
    self.percent = percent;
    [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    if (_percent == 1) {
        if (_isGray) {
           [self.starGrayImage drawInRect:rect];
        }else{
             [self.starHighLightImage drawInRect:rect];
            
        }
        return;
    }
    if (_percent == 0) {
        [self.starNormalImage drawInRect:rect];
        return;
    }
    CGFloat leftImageWidth = rect.size.width * _percent;
    CGFloat rightImageWidth = rect.size.width - leftImageWidth;
    UIImage * leftImage ;
    if (_isGray) {
         leftImage = [self segmentImage:self.starGrayImage percent:_percent fromLeft:YES];
     
    }else{
          leftImage = [self segmentImage:self.starNormalImage percent:_percent fromLeft:YES];
    }
    UIImage  * rightImage = [self segmentImage:self.starNormalImage percent:1-_percent fromLeft:NO];
    [leftImage drawInRect:CGRectMake(0, 0, leftImageWidth, rect.size.height)];
    [rightImage drawInRect:CGRectMake(leftImageWidth, 0, rightImageWidth, rect.size.height)];
}

- (UIImage *)segmentImage:(UIImage *)image percent:(CGFloat)percent fromLeft:(BOOL)left{
    
    CGSize sz = [image size];
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(sz.width*percent, sz.height), NO, 0);
    
    if (left) {
        [image drawAtPoint:CGPointMake(0, 0)];
    }else{
        [image drawAtPoint:CGPointMake(-(sz.width - sz.width*percent), 0)];
    }
    
    UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return im;
}





@end
